package com.csu.servlet;

import com.csu.entiry.BorrowInfo;
import com.csu.service.BorrowInfoService;
import com.csu.service.impl.BorrowInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.sql.Date;
import java.util.Queue;

@WebServlet(name = "AddBorrowInfoServlet", urlPatterns = "/AddBorrowInfoServlet")
public class AddBorrowInfoServlet extends HttpServlet {
    private BorrowInfoService borrowInfoService = new BorrowInfoServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
        System.out.println(12345);
        String bookname = req.getParameter("bookname");
        String  reader = req.getParameter("reader");

        String str = req.getParameter("borrowdate");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date d = null;
        try {
            d = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date date1 = new java.sql.Date(d.getTime());
        str = req.getParameter("returndate");
        try {
            d = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date date2 = new java.sql.Date(d.getTime());

        String SisReturn = req.getParameter("isReturn");
        int isReturn = (SisReturn != null) ? 1 : 0;

        BorrowInfo borrowInfo = new BorrowInfo();
        borrowInfo.setBookName(bookname);
        borrowInfo.setReader(reader);
        borrowInfo.setBorrowDate(date1);
        borrowInfo.setReturnDate(date2);

//        System.out.println(date1);
//        System.out.println(date2);

        borrowInfo.setIsReturn(isReturn);
        boolean result = borrowInfoService.addInfo(borrowInfo);
        if(result){
            req.getSession().setAttribute("msg", "添加成功！");
        }
        else{
            req.getSession().setAttribute("msg", "添加失败！");
        }
        resp.sendRedirect(req.getContextPath() + "/GetBorrowInfoServlet");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
